<template>
  <div class="container">
    <div class="auto">

      <div class="rule_wrap">
        <a-card hoverable>
          <span slot="title" v-if="!$route.query.worksId"><a-icon
            style="float: left; margin-top: 4px; margin-right: 8px; cursor: pointer" type="rollback" @click="goBack"/>新增作品</span>
          <span slot="title" v-else><a-icon style="float: left; margin-top: 4px; margin-right: 8px; cursor: pointer"
                                            type="rollback" @click="goBack"/>编辑作品</span>
          <a-spin :spinning="confirmLoading">
            <a-form :form="form">
              <a-row class="rowStyle">
                <a-col>
                  <a-button type="primary" @click="submit" style="float: right;">保存</a-button>
                </a-col>
              </a-row>
              <!-- <a-row  class="rowStyle">
                <span class="modelTitle">基础信息</span>
              </a-row> -->
              <a-row>
                <a-col span="12">
                  <a-col>
                    <a-form-item label="作品">
                      <a-input
                        placeholder="请输入作品!"
                        v-decorator="['worksName', validatorRules.worksName ]"/>
                    </a-form-item>
                  </a-col>
                  <a-col>
                    <a-form-item label="自定义顺序">
                      <a-input-number
                        style="width: 100%;"
                        placeholder="自定义顺序"
                        v-decorator="['seq', validatorRules.seq ]"/>
                    </a-form-item>
                  </a-col>
                  <a-col>
                    <a-form-item label="关键词">
                      <a-input v-decorator="['topic', {} ]" style="width: 100%"
                               placeholder='请输入关键词(使用"，"分割)!'></a-input>
                    </a-form-item>
                  </a-col>
                </a-col>
                <a-col span="10" offset="2">
                  <a-form-item label="缩略图">
                    <a-upload
                      v-if="isRender"
                      accept="image/*"
                      name="file"
                      :headers="headers"
                      :data="fileData"
                      :action="uploadUrl"
                      list-type="picture-card"
                      :default-file-list="fileList"
                      :remove="beforeRemove"
                      @preview="handlePreview"
                      @change="UploadhandleChange"
                      v-decorator="['lightPic',  validatorRules.lightPic ]"
                    >
                      <div v-if="fileList.length < 1">
                        <a-icon type="plus"/>
                        <div class="ant-upload-text">
                          上传
                        </div>
                      </div>
                    </a-upload>
                  </a-form-item>
                  <a-modal :visible="imgPreviewVisible" title="缩略图" @cancel="imgHandleCancel">
                    <img alt="example" style="width: 100%" :src="previewImage"/>
                    <template slot="footer">
                      <a-button key="back" @click="imgHandleCancel">关闭</a-button>
                    </template>
                  </a-modal>
                </a-col>
              </a-row>

              <a-row>
                <a-col span="12">
                  <a-form-item label="描述">
                    <a-textarea
                      placeholder="请输入对作品的简短描述，以便用户查看简略！"
                      v-decorator="['worksIntroduce', validatorRules.worksIntroduce ]" :autoSize="{ minRows: 6, maxRows: 12 }"/>
                  </a-form-item>
                </a-col>
              </a-row>
<!--              <a-row style="margin-bottom: 50px;">-->
<!--                <a-col span="23">-->
<!--                  <a-form-item-->
<!--                    label="详细描述"-->
<!--                    style="height: 300px">-->
<!--                    <j-editor v-decorator="['description',validatorRules.description]" triggerChange-->
<!--                              :max_height="300"></j-editor>-->
<!--                  </a-form-item>-->
<!--                </a-col>-->
<!--              </a-row>-->
            </a-form>
          </a-spin>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import {Modal} from 'ant-design-vue'
import BASE_URL from '../../../config'
import { TreeSelect } from 'ant-design-vue';
import JEditor from '@/moduleCompontent/JEditor'
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from  "@/store/mutation-types"
import pick from 'lodash.pick'
import '../../../public/css/style.css';
import { deleteAction, postAction,getAction } from '@/api/manage'
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  name: 'AddStaffAndWorkers',
  components: {
    JEditor
  },
  beforeRouteEnter (to, from, next) {
    window.scrollTo(0, 0);
    if(Vue.ls.get(USER_INFO) && Vue.ls.get(USER_INFO).username && Vue.ls.get(USER_INFO).role == '1') {
      next()
    } else {
      next({
        path: '/home'
      })
    }
  },
  // beforeRouteLeave (to, from, next) {
  //   this.$confirm({
  //     title: '警告',
  //     content: '人员信息未保存，确定要退出吗?',
  //     okText: '退出',
  //     okType: 'danger',
  //     cancelText: '取消',
  //     onOk() {
  //       next()
  //     },
  //     onCancel() {
  //       next(false)
  //     },
  //   });
  // },
  data () {
    return {
      replaceFields: {
        value: 'id',
        title: 'name',
        key: 'id',
        children: 'children'
      },
      departTree: [],
      confirmLoading: false,
      uploadUrl: BASE_URL + '/article/upload',
      isRender: false,
      SHOW_PARENT,
      fileList: [],
      imgPreviewVisible: false,
      previewImage: '',
      // 上传头部token
      headers: {
        'token': Vue.ls.get(ACCESS_TOKEN)
      },
      // 上传附带参数
      fileData: {
        createBy: Vue.ls.get(USER_INFO).username || '游客',
      },
      model: {},
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      validatorRules: {
        worksName: {rules: [{required: true, message: '请输入作品!'}]},
        seq: {},
        worksIntroduce: {rules: [{required: true, message: '请输入对该作品的简短描述，以便用户查看简略!'}]},
        lightPic: {
          getValueFromEvent: this.normFile,
          rules: [{required: true, message: '请选择上传头像!'}]},

      }
    };
  },
  created() {
    let self = this
    this.getArticleList()
    this.$nextTick(() => {
      if(this.$route.query.worksId) {
        this.confirmLoading = true
        let url = '/works/info/' + this.$route.query.worksId
        getAction(url, {}).then(res => {
          if(res.code == 0) {

            self.model = Object.assign({}, res.result)
            self.model.lightPic = res.result.worksImg
            self.fileList = [
              {
                uid: '1',
                name: res.result.worksName,
                url: res.result.worksImg,
                status: 'done'
              }
            ]
            this.isRender = true
            this.form.setFieldsValue(pick(this.model,'worksName', 'topic', 'seq', 'worksIntroduce', 'lightPic'))
          } else {
            self.$message.error(res.msg)
          }
        }).finally(() => {
          self.confirmLoading = false
        })
      } else {
        this.isRender = true
        this.form.setFieldsValue(pick(this.model,'worksName', 'topic', 'seq', 'worksIntroduce', 'lightPic'))
      }
    });
  },
  methods: {
    getArticleList() {
      let self = this
      getAction('/column/listall', {parentId: 52}).then(res => {
        if(res.code == 0) {
          self.departTree = [...res.result]
        } else {
          self.$message.error(res.msg)
        }
      })
    },
    UploadhandleChange(info) {

      if (info.file.status === 'done') {
        if(info.file.response.code != 0) {
          if (info.file.response.code == 401){
            if(info.file.response.msg.includes("invalid token")) {
              Modal.error({
                title: '登录已过期',
                content: '很抱歉，登录已过期，请重新登录',
                okText: '重新登录',
                mask: false,
                onOk: () => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  Vue.ls.remove(USER_INFO)
                  window.location.href="/"
                }
              })
            } else {
              this.$message.error(`${info.file.name} ${info.file.response.msg}.`)
            }
          }
        } else {

          console.log(info)
          console.log(info.file.response.result.fileurl)
          this.fileList.push({

            uid: this.fileList.length + 1,
            name: info.file.response.result.filename,
            status: 'done',
            url: info.file.response.result.fileurl,
          })
          this.$message.success('上传成功!')
        }
      } else if (info.file.status === 'error') {
        if (info.file.response.status === 500) {
          this.$message.error(`文件上传失败: ${info.file.msg} `);
        } else {
          Modal.error({
            title: '登录已过期',
            content: '很抱歉，登录已过期，请重新登录',
            okText: '重新登录',
            mask: false,
            onOk: () => {
              Vue.ls.remove(ACCESS_TOKEN)
              Vue.ls.remove(USER_INFO)
              window.location.href="/"
              // window.location.reload()
            }
          })
        }
      }
    },
    normFile(e) {
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    },
    submit() {

      let self = this
      if(this.fileList.length) {
        self.form.setFieldsValue({
          'lightPic': this.fileList
        })
      } else {
        self.form.setFieldsValue({
          'lightPic': undefined
        })
      }
      this.form.validateFields((err, value) => {
        if (!err) {
          let formData = Object.assign(this.model, value);
          formData.worksImg = self.fileList[0].url
          delete  formData.lightPic
          let url
          if(self.$route.query.worksId) {
            url = '/works/update'
          } else {
            url = '/works/save'
          }
          postAction(url, formData).then(res => {
            if(res.code == 0) {
              self.$message.success(res.msg)
              self.confirmLoading = false
              self.$router.push({path: '/worksShow'})
            } else {
              self.$message.error(res.msg)
              self.confirmLoading = false
            }
          })
        }
      })
    },
    imgHandleCancel() {
      this.imgPreviewVisible = false;
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file]
      return false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.imgPreviewVisible = true;
    },
    beforeRemove(file) {
      let self = this
      let url
      if (file.response) {
        url = file.response.result.fileurl
      } else {
        url = file.url
      }
      let index
      for(let x in this.fileList) {
        if(this.fileList[x].url == url) {
          index = x
        }
      }
      return new Promise((resolve, reject) => {
        this.$confirm({
          title: '确认要移除此图片?',
          onOk() {
            self.fileList.splice(index,1)
            self.form.setFieldsValue({
              'lightPic': undefined
            })
            resolve()
          },
          onCancel() {
            resolve(false)
          }
        })
      })
    },
    goBack() {
      this.$router.go(-1)
    }
  }
};
</script>

<style lang="less">
  .AddStaffAndWorkers {
    .rowStyle {
      margin-bottom: 20px;
    }
    .modelTitle {
      font-size: 14px;
      font-weight: 700;
    }
    // .avatar-uploader > .ant-upload {
    //   width: 128px;
    //   height: 128px;
    // }
    // .ant-upload-select-picture-card i {
    //   font-size: 32px;
    //   color: #999;
    // }

    // .ant-upload-select-picture-card .ant-upload-text {
    //   margin-top: 8px;
    //   color: #666;
    // }
    .ant-upload.ant-upload-select-picture-card {
      width: 241px;
      height: 241px;
    }
    .ant-upload-list-picture-card .ant-upload-list-item {
      width: 241px;
      height: 241px;
    }
  }
</style>
